package com.wll.exportfile.utils;

import cn.hutool.core.util.RandomUtil;

import java.io.UnsupportedEncodingException;
import java.util.Random;

public class HanziUtils {


    public static String getRandomHanZi(int start, int end) {
        String han = "";
        for (int i = 0; i < RandomUtil.randomInt(start, end); i++) {
            han += getHanZi() + "";
        }
        return han;
    }

    public static String getRandomHanZi() {
        String han = "";
        for (int i = 0; i < RandomUtil.randomInt(10, 100); i++) {
            han += getHanZi() + "";
        }
        return han;
    }

    static String getHanZi() {
        Random random = new Random();///随机数
        String[] rBase = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        // 生成第1位的区码
        int r1 = random.nextInt(3) + 11; //生成11到14之间的随机数
        String str_r1 = rBase[r1];
        // 生成第2位的区码
        int r2;
        if (r1 == 13) {
            r2 = random.nextInt(7); //生成0到7之间的随机数
        } else {
            r2 = random.nextInt(16); //生成0到16之间的随机数
        }
        String str_r2 = rBase[r2];
        // 生成第1位的位码
        int r3 = random.nextInt(6) + 10; //生成10到16之间的随机数
        String str_r3 = rBase[r3];
        // 生成第2位的位码
        int r4;
        if (r3 == 10) {
            r4 = random.nextInt(15) + 1; //生成1到16之间的随机数
        } else if (r3 == 15) {
            r4 = random.nextInt(15); //生成0到15之间的随机数
        } else {
            r4 = random.nextInt(16); //生成0到16之间的随机数
        }
        String str_r4 = rBase[r4];
//        System.out.println(str_r1 + str_r2 + str_r3 + str_r4);
        // 将生成机内码转换为汉字
        byte[] bytes = new byte[2];
        //将生成的区码保存到字节数组的第1个元素中
        String str_r12 = str_r1 + str_r2;
        int tempLow = Integer.parseInt(str_r12, 16);
        bytes[0] = (byte) tempLow;
        //将生成的位码保存到字节数组的第2个元素中
        String str_r34 = str_r3 + str_r4;
        int tempHigh = Integer.parseInt(str_r34, 16);
        bytes[1] = (byte) tempHigh;
        String ctmp = null; //根据字节数组生成汉字
        try {
            ctmp = new String(bytes, "gb2312");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
//        System.out.println("生成汉字:" + ctmp);
        return ctmp;
    }


}
